<?php

namespace app\components;

use Yii;
use app\components\BaseController;
use app\models\AccessToken;
use app\components\Log;
use app\models\Tenant;
use yii\web\ServerErrorHttpException;
use app\components\Wechat;
use app\components\Loyalty;
use app\models\MemberCardMap;

/**
 * 微信基础控制器
 * 微信通用功能
 */
class BaseWechatController extends BaseController
{
    const APPID = 'wxeca2e361be1de14c';

    const APPSECRET = '28e9d3fb572104e1bef285d20fa760c5';

    public $layout = 'wechat';
    
    public $enableCsrfValidation = false;
    
    public $openid;
    
    public $wxid;

    public function getAccessToken()
    {
        return Wechat::config('access_token');
    }

    public function response()
    {
        // $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postData = file_get_contents('php://input');
//         Log::debug('postData', $postData);
        if (!empty($postData)) {
            $xml = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
//             Log::debug('xml', $xml);
            $this->openid = (string)$xml->FromUserName;
            $this->wxid = (string)$xml->ToUserName;
            $msgType = (string)$xml->MsgType;
            
            // 消息
            if ($msgType == 'text') {
                $content = (string)$xml->Content;
                $this->text($content);
            // 事件
            } elseif ($msgType == 'event') {
                $eventKey = $xml->EventKey;
                $event = $xml->Event;
//                 Log::debug('事件名称', $event);
                if ($event == 'subscribe') {
//                     Log::debug('关注事件回复', $this->text($ToUserName, $FromUserName, $Content));
                    echo $this->xmlImageText('测试', '这是测试信息', 'https://mmbiz.qpic.cn/mmbiz_jpg/UzsLSJicrzHdQb3012ncQrAAxLlTEHUUib3xP8mSDgxxnFbCrZyGhJp2BpIG2yJFUaBbh3tqCubjJ2Wz2EgkqSJQ/0?wx_fmt=jpeg', 'http://winshare.onthemooner.com/index.php/member/register');
                } elseif ($event == 'SCAN') {
                    $content = (string)$xml->Ticket;
//                     Log::debug('场景id', $content);
                    echo $this->text($content);
                // 用户领取卡券
                } elseif ($event == 'user_get_card') { 
                    $card_code = (string)$xml->UserCardCode; // 强转以保证数据格式正确
                    $card_id = (string)$xml->CardId;
                    $create_time = (string)$xml->CreateTime;

                    $map = MemberCardMap::find()->where(['openid' => $this->openid, 'cardid' => $card_id])->one();
//                     Log::debug('领卡前查询该会员卡', $map);
                    if ($map) {
//                         Log::debug('会员卡重复', $openid . '_' . $create_time);
                    } else {
//                     	Log::debug('创建领卡记录');
                        $map = new MemberCardMap;
                        $map->openid = $this->openid;
                        $map->cardid = $card_id;
                        $map->cardcode = $card_code;
                        $map->status = MemberCardMap::STATUS_GETCARD;
                        $map->getcard_at = $create_time;
                        $map->activate_at = 0;
                        $map->save();
                    }
                    $this->replynull();
                // 用户激活会员卡
                } elseif ($event == 'submit_membercard_user_info') {  
                    $card_code = (string)$xml->UserCardCode;
                    $card_id = (string)$xml->CardId;
                    $create_time = (string)$xml->CreateTime;

                    $map = MemberCardMap::find()->where(['openid' => $this->openid, 'cardid' => $card_id])->one();
//                     Log::debug('激活前查询该会员卡', $map);
                    if ($map) {
                    	if ($map['activate_at'] == $create_time) {
//                     		Log::debug('激活会员卡重复', $openid . '_' . $create_time);
                    	} else {
//                     		Log::debug('创建激活卡记录');
                    		$map->status = MemberCardMap::STATUS_ACTIVATE;
                    		$map->activate_at = $create_time;
                    		$map->save();
                    	}
                    }
                   	$this->replynull();
//                     if (!empty($map) && $map['modified_at'] == $Createtime) {
//                         Log::debug('激活会员卡重复', $openid . $createtime);
//                         return true;
//                     } else {
//                         if (!empty($map)) {
//                             $map->status = 2;
//                             $map->save();
//                         } else {
//                             $map = new MemberCardMap();
//                             $map->openid = $opendid;
//                             $map->cardid = $cardid;
//                             $map->cardcode = $cardcode;
//                             $map->status = 2;
//                             $map->modified_at = $createtime;
//                             $map->save();
//                             return true;
//                         }
//                     }
                }
            }
        } else {
//             Log::debug('未接受到微信的请求');
        }
    }
    
    /**
     * 返回普通文本消息
     * @param string $content
     */
    public function text($content)
    {
    	$response = "
    	<xml>
    	<ToUserName><![CDATA[{$this->openid}]]></ToUserName>
    	<FromUserName><![CDATA[{$this->wxid}]]></FromUserName>
    	<CreateTime>" . time() . "</CreateTime>
    	<MsgType><![CDATA[text]]></MsgType>
    	<Content><![CDATA[{$content}]]></Content>
    	</xml>";
    	//         Log::debug('echo xml', $text);
//     	echo $response;	
    }
    
    /**
     * 回复空字符串避免重复消息
     */
    public function replynull()
    {
    	echo '';
    }

    public function res()
    {
        $postData = file_get_contents('php://input');
        Log::debug('postData', $postData);
    }
    
    //回复图文类型消息模板
    public function xmlImageText($Title, $Description, $PicUrl, $Url)
    {
        $response = "
                <xml>
                <ToUserName><![CDATA[{$this->openid}]]></ToUserName>
                <FromUserName><![CDATA[{$this->wxid}]]></FromUserName>
                <CreateTime>" . time() . "</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>1</ArticleCount>
                <Articles>
                <item>
                <Title><![CDATA[{$Title}]]></Title> 
                <Description><![CDATA[{$Description}]]></Description>
                <PicUrl><![CDATA[{$PicUrl}]]></PicUrl>
                <Url><![CDATA[{$Url}]]></Url>
                </item>
                </Articles>
                </xml>";
        echo $response;
    }

    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 微信服务器验证 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    public function valid()
    {
        $echoStr = $_GET['echostr'];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function checkSignature()
    {
        $signatrue = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $token = 'XGATE';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signatrue) {
            return true;
        } else {
            return false;
        }
    }
    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 微信服务器验证 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<   

    // >>>>>>>>>>>>>>>>>>>>>>>>>>> 确保tenant 唯一性的措施 start <<<<<<<<<<<<<<<<<<<<<<<<
    public function setConfig($appid, $openid)
    {
        // 删除session,重新设置appid
    	
        $session = Yii::$app->session;
        $session->destroy();
        $this->setAppid($appid);
        
        // 设置identifier
        $tenant = Tenant::find()->where(['appid' => $appid])->one();
        if (empty($tenant->identifier)) {
            throw new ServerErrorHttpException('identifier not found');
        }

        // 设置loyalty config
        if (empty($tenant->tenant_id) || empty($tenant->loyalty_accountid) || empty($tenant->loyalty_username) || empty($tenant->loyalty_password)) {
            throw new ServerErrorHttpException('loyalty config not found');
        } else {
            $loyaltyConfig = [
                'tenant_id' => $tenant->tenant_id,
                'app_id' => $tenant->appid,
                'loyalty_accountid' => $tenant->loyalty_accountid,
                'loyalty_username' => $tenant->loyalty_username,
                'loyalty_password' => $tenant->loyalty_password,
                'loyalty_url' => $tenant->loyalty_url,
            ];
            $session->set('loyaltyConfig', $loyaltyConfig);
        }

        // 保存用户基础信息
        if (!empty($openid) && isset($openid)) {
            $this->setOpenid($openid);
        }
    }

    //激活会员卡api
    public function ActivateMemberCard($code, $points)
    {
        $data = [
            "init_bonus" => $points,
            "init_bonus_record" => "旧积分同步",
            "membership_number" => "MOMO01",
            "code" => "$code",
        ];
        return Wechat::card_activate($data);
    }

    //报错页面
    public function error($message, $code = null)
    {
        $this->redirect(['errors/index', 'message' => $message, 'code' => $code]);
    }

    // >>>>>>>>>>>>>>>>>>>>>>>>>>> 确保tenant 唯一性的措施 end   <<<<<<<<<<<<<<<<<<<<<<<<
}
